package com.bear.atlassianmcp.confluence.mcp.tools;

import com.bear.atlassianmcp.confluence.model.ConfluenceSpace;
import com.bear.atlassianmcp.confluence.service.ConfluenceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Confluence空间管理MCP工具
 * 提供空间查询、空间统计等功能
 */
@Service
public class ConfluenceSpaceTools {

    private static final Logger logger = LoggerFactory.getLogger(ConfluenceSpaceTools.class);

    private final ConfluenceService confluenceService;

    @Autowired
    public ConfluenceSpaceTools(ConfluenceService confluenceService) {
        this.confluenceService = confluenceService;
    }

    /**
     * 获取所有可访问的空间列表
     *
     * @param context 工具上下文
     * @return 空间列表的格式化文本
     */
    @Tool(description = "获取当前用户可以访问的所有Confluence空间列表，包括空间键、名称、描述等信息")
    public String getSpaces(ToolContext context) {
        logger.info("MCP Tool: Getting all Confluence spaces");

        try {
            List<ConfluenceSpace> spaces = confluenceService.getSpaces(context);
            
            if (spaces.isEmpty()) {
                return "🏠 当前没有可访问的空间。";
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("🏠 可访问的空间列表 (共%d个)：\n\n", spaces.size()));
            
            for (int i = 0; i < spaces.size(); i++) {
                ConfluenceSpace space = spaces.get(i);
                result.append(String.format("%d. %s (%s)\n", 
                                           i + 1, space.getName(), space.getKey()));
                
                String desc = space.getDescriptionText();
                if (desc != null && !desc.trim().isEmpty()) {
                    if (desc.length() > 100) {
                        desc = desc.substring(0, 100) + "...";
                    }
                    result.append(String.format("   📝 描述: %s\n", desc));
                }
                
                result.append(String.format("   📂 类型: %s\n", space.getType()));
                result.append(String.format("   📊 状态: %s\n", space.getStatus()));
                
                result.append("\n");
            }
            
            logger.info("Successfully retrieved {} spaces via MCP", spaces.size());
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get spaces via MCP: {}", e.getMessage());
            return "❌ 获取空间列表失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取指定空间的详细信息
     *
     * @param spaceKey 空间键值，如"DEMO"
     * @param context 工具上下文
     * @return 空间详细信息的格式化文本
     */
    @Tool(description = "获取指定Confluence空间的详细信息，包括空间配置、描述等")
    public String getSpace(@ToolParam(description = "空间键值，如DEMO、PROJ等，可通过getSpaces工具获取") String spaceKey, ToolContext context) {
        logger.info("MCP Tool: Getting Confluence space details for {}", spaceKey);

        try {
            ConfluenceSpace space = confluenceService.getSpace(spaceKey, context);
            String result = space.toFormattedString();
            
            logger.info("Successfully retrieved space {} via MCP", spaceKey);
            return result;
            
        } catch (Exception e) {
            logger.error("Failed to get space {} via MCP: {}", spaceKey, e.getMessage());
            return "❌ 获取空间详情失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取空间简要信息列表
     *
     * @param context 工具上下文
     * @return 空间简要信息列表
     */
    @Tool(description = "获取所有空间的简要信息列表，只包含空间键和名称，适合快速浏览")
    public String getSpacesSummary(ToolContext context) {
        logger.info("MCP Tool: Getting Confluence spaces summary");

        try {
            List<ConfluenceSpace> spaces = confluenceService.getSpaces(context);
            
            if (spaces.isEmpty()) {
                return "🏠 当前没有可访问的空间。";
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("🏠 空间简要列表 (共%d个)：\n", spaces.size()));
            
            for (ConfluenceSpace space : spaces) {
                result.append(String.format("• %s (%s)", space.getName(), space.getKey()));
                result.append(String.format(" - 类型: %s", space.getType()));
                result.append("\n");
            }
            
            logger.info("Successfully retrieved spaces summary via MCP: {} spaces", spaces.size());
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get spaces summary via MCP: {}", e.getMessage());
            return "❌ 获取空间简要列表失败。原因：" + e.getMessage();
        }
    }

    /**
     * 测试Confluence连接
     * 
     * @return 连接测试结果
     */
    @Tool(description = "测试与Confluence服务器的连接状态，验证认证和网络连通性")
    public String testConfluenceConnection(ToolContext toolContext) {
        logger.info("MCP Tool: Testing Confluence connection");
        
        try {
            String result = confluenceService.testConnection(toolContext);
            
            logger.info("Successfully tested Confluence connection via MCP");
            return "🔗 " + result;
            
        } catch (Exception e) {
            logger.error("Failed to test Confluence connection via MCP: {}", e.getMessage());
            return "❌ 连接测试失败。原因：" + e.getMessage() + 
                   "\n💡 请检查Confluence服务器地址、用户名和密码配置。";
        }
    }
}
